package com.gcsoftware.utils.mail;

import com.gcsoftware.utils.MapUtils;
import com.gcsoftware.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.validation.constraints.AssertFalse;
import java.util.Properties;

/**
 * Created by qs on 2018/3/23.
 */
public class MailUtils {
    private static Logger logger = LoggerFactory.getLogger(MapUtils.class);

    public static final String DEFALUT_ENCODING = "UTF-8";

    private static JavaMailSender mailSender = SpringContextUtils.getBean(JavaMailSender.class);

    public static void sendMail(SendMailInfo info) throws Exception {
        sendMail(info.getDeliver(),new String[]{info.getReceiver()},null,info.getSubject(),info.getContent(),info.isHtml());

    }
    public static void sendMail(String deliver, String[] receiver, String[] carbonCopy, String subject, String content, boolean isHtml) throws Exception {
        long startTimestamp = System.currentTimeMillis();
        logger.info("Start send email ...");

        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(message);

            messageHelper.setFrom(deliver);
            messageHelper.setTo(receiver);
            if (null != carbonCopy && carbonCopy.length > 0)
                messageHelper.setCc(carbonCopy);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, isHtml);

            new SendMailTask(mailSender,message,startTimestamp).start();
            /*mailSender.send(message);
            logger.info("Send email success, cost {} million seconds", System.currentTimeMillis() - startTimestamp);*/
        } catch (MessagingException e) {
            logger.error("Send email failed, error message is {} \n", e.getMessage());
            e.printStackTrace();
            throw new Exception(e);
        }

    }

}
